<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import loginApi from '../api/login_api.js'
import userApi from '../api/user_api.js'  // 添加用户API
import { User, Message, Lock, Key } from '@element-plus/icons-vue';

const admin = ref({
  adminname: '',
  email: '',
  password: '',
  captcha: '',
  key: ''
});

// 用户登录数据
const user = ref({
  username: '',
  email: '',
  password: '',
  captcha: '',
  key: ''
});

// 用户注册数据
const registerUser = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
});

// 邮箱登录数据
const emailLogin = ref({
  email: '',
  code: '',
  codeText: '发送验证码',
  isCounting: false
});

// 登录方式：password 或 email
const loginType = ref('password');

// 登录角色：admin 或 user
const loginRole = ref('admin');

// 页面状态：login 或 register
const pageState = ref('login');

// 角色选项
const roleOptions = ref([
  { label: '管理员登录', value: 'admin' },
  { label: '用户登录', value: 'user' }
]);

// 获取路由对象
const router = useRouter();

// 验证码图片数据
const captcha = ref("");
let countdownTimer = null;

onMounted(function (){
  localStorage.removeItem("token");
  // 加载验证码
  loadCaptcha();

  const video=document.getElementById('bg-video');
  const poster=document.getElementById('video-poster');
  video.addEventListener('loadeddata',()=>{
    poster.style.display="none";
  })
})

// 登录提交
const onSubmit = async () => {
  try {
    let res;

    if (loginRole.value === 'admin') {
      // 管理员登录
      if (loginType.value === 'password') {
        // 使用现有的管理员登录接口
        res = await loginApi.login({
          adminname: admin.value.adminname,
          email: admin.value.email,
          password: admin.value.password,
          captcha: admin.value.captcha,
          key: admin.value.key
        });
      } else {
        // 使用已有的管理员邮箱登录接口
        res = await loginApi.loginByEmail(emailLogin.value.email, emailLogin.value.code);
      }
    } else {
      // 用户登录
      if (loginType.value === 'password') {
        // 使用现有的用户登录接口
        res = await loginApi.loginUser({
          username: user.value.username,
          email: user.value.email,
          password: user.value.password,
          captcha: user.value.captcha,
          key: user.value.key
        });
      } else {
        // 使用已有的用户邮箱登录接口
        res = await loginApi.loginUserByEmail(emailLogin.value.email, emailLogin.value.code);
      }
    }

    if (res) {
      localStorage.setItem("token", res);
      localStorage.setItem("role", loginRole.value); // 保存角色
      ElMessage.success("登录成功");

      if (loginRole.value === 'admin') {
        localStorage.setItem("username", admin.value.adminname); // 保存管理员名
        router.push("/admin");
      } else {
        const userInfo = await loginApi.userinfo();
        if (userInfo && userInfo.id) {
          localStorage.setItem("userId", userInfo.id); // 保存用户ID
        }
        localStorage.setItem("username", user.value.username); // 保存用户名
        router.push("/carousel");
      }
    }
    else {
      ElMessage.error("登录失败，请检查账号密码或验证码");
      if (loginType.value === 'password') {
        loadCaptcha();
      }
    }
  } catch (error) {
    console.error("登录错误:", error);
    ElMessage.error("登录失败: " + (error.message || "未知错误"));
    if (loginType.value === 'password') {
      loadCaptcha();
    }
  }
}

// 用户注册
const onRegister = async () => {
  // 表单验证
  if (!registerUser.value.username || !registerUser.value.email ||
      !registerUser.value.password || !registerUser.value.confirmPassword) {
    ElMessage.warning("请填写所有必填项");
    return;
  }

  if (registerUser.value.password !== registerUser.value.confirmPassword) {
    ElMessage.warning("两次输入的密码不一致");
    return;
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(registerUser.value.email)) {
    ElMessage.warning("请输入正确的邮箱格式");
    return;
  }

  try {
    // 调用用户注册API
    const res = await userApi.add({
      username: registerUser.value.username,
      email: registerUser.value.email,
      password: registerUser.value.password
    });

    if (res) {
      ElMessage.success("注册成功，请登录");
      // 切换回登录页面
      pageState.value = 'login';
      // 重置注册表单
      registerUser.value = {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      };
    } else {
      ElMessage.error("注册失败");
    }
  } catch (error) {
    console.error("注册错误:", error);
    ElMessage.error("注册失败: " + (error.message || "未知错误"));
  }
}

// 加载验证码
const loadCaptcha = async () => {
  try {
    const res = await loginApi.captcha();
    if (res) {
      if (loginRole.value === 'admin') {
        admin.value.key = res.key || '';
      } else {
        user.value.key = res.key || '';
      }
      captcha.value = res.base || '';
    }
  } catch (error) {
    console.error("验证码加载失败:", error);
    ElMessage.error("验证码加载失败");
  }
}

const sendEmailCode = async () => {
  if (!emailLogin.value.email) {
    ElMessage.warning("请输入邮箱地址");
    return;
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(emailLogin.value.email)) {
    ElMessage.warning("请输入正确的邮箱格式");
    return;
  }

  try {
    let res;
    if (loginRole.value === 'admin') {
      res = await loginApi.sendEmailCode(emailLogin.value.email);
    } else {
      res = await loginApi.sendUserEmailCode(emailLogin.value.email);
    }

    if (res) {
      ElMessage.success("验证码已发送，请查收邮箱");
      startCountdown();
    } else {
      ElMessage.error("验证码发送失败");
    }
  } catch (error) {
    ElMessage.error("验证码发送失败: " + (error.message || "未知错误"));
  }
}

// 倒计时功能
const startCountdown = () => {
  emailLogin.value.isCounting = true;
  let count = 60;
  emailLogin.value.codeText = `${count}秒后重发`;

  countdownTimer = setInterval(() => {
    count--;
    if (count > 0) {
      emailLogin.value.codeText = `${count}秒后重发`;
    } else {
      emailLogin.value.codeText = '发送验证码';
      emailLogin.value.isCounting = false;
      clearInterval(countdownTimer);
    }
  }, 1000);
}

// 切换登录方式
const switchLoginType = (type) => {
  loginType.value = type;
  // 清除倒计时
  if (countdownTimer) {
// ... existing code ...

    clearInterval(countdownTimer);
    emailLogin.value.codeText = '发送验证码';
    emailLogin.value.isCounting = false;
  }
}

// 切换登录角色
const switchLoginRole = (role) => {
  loginRole.value = role;
  // 重置表单数据
  admin.value = {
    adminname: '',
    email: '',
    password: '',
    captcha: '',
    key: ''
  };

  user.value = {
    username: '',
    email: '',
    password: '',
    captcha: '',
    key: ''
  };

  emailLogin.value = {
    email: '',
    code: '',
    codeText: '发送验证码',
    isCounting: false
  };

  // 重新加载验证码
  loadCaptcha();
}
</script>

<template>
  <div class="login-container">
    <div class="video-bg-container">
      <img id="video-poster" src="@/assets/back.jpeg" alt="背景图" class="video-poster">
      <video id="bg-video" class="bg-video"
             autoplay
             muted
             loop
             playsinline
             poster="@/assets/back.jpeg">
        <source src="../assets/backvideo.mp4" type="video/mp4">
      </video>
      <div class="video-overlay"></div>
    </div>
  </div>
  <div class="login-bg">
    <!-- 页面状态切换 -->
    <div class="page-toggle">
      <el-button v-if="pageState === 'register'" link @click="pageState = 'login'">
        已有账号？去登录
      </el-button>
      <el-button v-else link @click="pageState = 'register'">
        没有账号？去注册
      </el-button>
    </div>

    <!-- 注册表单 -->
    <el-form v-if="pageState === 'register'" class="form-login" :model="registerUser">
      <div class="form-header">
        <img class="logo" src="@/assets/logo.png" alt="旅小帮" />
        <h1>用户注册</h1>
      </div>

      <div class="form-fields">
        <el-form-item>
          <el-input v-model="registerUser.username"
                    placeholder="请输入用户名"
                    maxlength="16">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-input v-model="registerUser.email"
                    placeholder="请输入邮箱"
                    maxlength="50">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-input v-model="registerUser.password"
                    placeholder="请输入密码"
                    show-password
                    maxlength="20">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-input v-model="registerUser.confirmPassword"
                    placeholder="请确认密码"
                    show-password
                    maxlength="20">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </div>

      <el-form-item>
        <el-button class="btn-login" type="success" @click="onRegister">注册</el-button>
      </el-form-item>
    </el-form>

    <!-- 登录表单 -->
    <div v-else>
      <!-- 角色切换 -->
      <div class="role-switch">
        <el-segmented
          v-model="loginRole"
          :options="roleOptions"
          @change="switchLoginRole"
          block
        />
      </div>

      <!-- 管理员登录表单 -->
      <el-form v-if="loginRole === 'admin'" class="form-login" :model="admin">
        <div class="form-header">
          <img class="logo" src="@/assets/logo.png" alt="旅小帮" />
          <h1>管理员登录</h1>
        </div>

        <!-- 登录方式切换 -->
        <div class="login-type-switch">
          <el-button
              :type="loginType === 'password' ? 'primary' : 'default'"
              @click="switchLoginType('password')"
              size="small"
              class="switch-btn"
          >
            密码登录
          </el-button>
          <el-button
              :type="loginType === 'email' ? 'primary' : 'default'"
              @click="switchLoginType('email')"
              size="small"
              class="switch-btn"
          >
            邮箱验证码登录
          </el-button>
        </div>

        <div v-if="loginType === 'password'" class="form-fields">
          <el-form-item>
            <el-input v-model="admin.adminname"
                      placeholder="请输入管理员账号"
                      maxlength="16">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-input v-model="admin.email"
                      placeholder="请输入邮箱"
                      maxlength="50">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-input v-model="admin.password"
                      placeholder="请输入密码"
                      show-password
                      maxlength="20">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="captcha-field">
            <el-input v-model="admin.captcha"
                      placeholder="验证码"
                      maxlength="5"
                      class="input-verCode">
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <img :src="captcha"
                 class="img-verCode" @click="loadCaptcha" alt="验证码">
          </el-form-item>
        </div>

        <div v-else class="form-fields">
          <el-form-item>
            <el-input v-model="emailLogin.email"
                      placeholder="请输入邮箱"
                      maxlength="50">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="code-field">
            <el-input v-model="emailLogin.code"
                      placeholder="请输入验证码"
                      maxlength="6"
                      class="input-code">
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <el-button
                @click="sendEmailCode"
                :disabled="emailLogin.isCounting"
                class="send-code-btn"
                type="primary"
            >
              {{ emailLogin.codeText }}
            </el-button>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button class="btn-login" type="success" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户登录表单 -->
      <el-form v-else class="form-login" :model="user">
        <div class="form-header">
          <img class="logo" src="@/assets/logo.png" alt="旅小帮" />
          <h1>用户登录</h1>
        </div>

        <!-- 登录方式切换 -->
        <div class="login-type-switch">
          <el-button
              :type="loginType === 'password' ? 'primary' : 'default'"
              @click="switchLoginType('password')"
              size="small"
              class="switch-btn"
          >
            密码登录
          </el-button>
          <el-button
              :type="loginType === 'email' ? 'primary' : 'default'"
              @click="switchLoginType('email')"
              size="small"
              class="switch-btn"
          >
            邮箱验证码登录
          </el-button>
        </div>

        <div v-if="loginType === 'password'" class="form-fields">
          <el-form-item>
            <el-input v-model="user.username"
                      placeholder="请输入用户名"
                      maxlength="16">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-input v-model="user.email"
                      placeholder="请输入邮箱"
                      maxlength="50">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-input v-model="user.password"
                      placeholder="请输入密码"
                      show-password
                      maxlength="20">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="captcha-field">
            <el-input v-model="user.captcha"
                      placeholder="验证码"
                      maxlength="5"
                      class="input-verCode">
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <img :src="captcha"
                 class="img-verCode" @click="loadCaptcha" alt="验证码">
          </el-form-item>
        </div>

        <div v-else class="form-fields">
          <el-form-item>
            <el-input v-model="emailLogin.email"
                      placeholder="请输入邮箱"
                      maxlength="50">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="code-field">
            <el-input v-model="emailLogin.code"
                      placeholder="请输入验证码"
                      maxlength="6"
                      class="input-code">
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <el-button
                @click="sendEmailCode"
                :disabled="emailLogin.isCounting"
                class="send-code-btn"
                type="primary"
            >
              {{ emailLogin.codeText }}
            </el-button>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button class="btn-login" type="success" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>



<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

/* 页面切换按钮 */
.page-toggle {
  align-self: flex-end;
  margin-bottom: 10px;
}

/* 视频背景层 */
.video-bg-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  filter: brightness(1.3);
}

.bg-video,
.video-poster {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.2); /* 黑色半透明遮罩，突出表单 */
  z-index: 2;
}

/* 登录表单层，始终居中 */
.login-bg {
  position: absolute;   /* ✅ 绝对定位 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* ✅ 居中关键 */
  z-index: 999;         /* ✅ 保证在视频和遮罩上方 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 360px;         /* 表单宽度 */
  padding: 30px;
  background: rgba(255, 255, 255, 0.1); /* 白色半透明背景 */
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
}

/* 角色切换按钮 */
.role-switch {
  display: flex;
  justify-content: center;
  gap: 35px;
  margin-bottom: 30px;
}

/* 表单头部 */
.form-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  width: 100%;
}

.logo {
  width: 150px;
  height: 60px;
  margin-right: 15px;
}

.form-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

/* 登录方式切换 */
.login-type-switch {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
  width: 100%;
}

.switch-btn {
  flex: 1;
}

/* 表单字段 */
.form-fields {
  width: 100%;
}

.form-login :deep(.el-form-item) {
  margin-bottom: 20px;
}

.form-login :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-login :deep(.el-input__prefix) {
  padding-left: 10px;
}

/* 验证码字段 */
.captcha-field {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-verCode {
  flex: 1;
}

.img-verCode {
  width: 100px;
  height: 40px;
  cursor: pointer;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  object-fit: cover;
}

/* 邮箱验证码字段 */
.code-field {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-code {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  height: 40px;
}

/* 登录按钮 */
.btn-login {
  width: 100%;
  height: 45px;
  margin-top: 10px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-bg {
    width: 90%;
    padding: 20px;
  }

  .form-header h1 {
    font-size: 20px;
  }

  .login-type-switch {
    flex-direction: column;
    gap: 8px;
  }

  .captcha-field,
  .code-field {
    flex-direction: column;
    align-items: stretch;
  }

  .img-verCode,
  .send-code-btn {
    width: 100%;
    margin-left: 0;
    margin-top: 10px;
  }
}
</style>

